# -*- coding:utf-8 -*-

import xlsxwriter


class ExcelUtil:
    """
    将数据写入到Excel中
    """
    def __init__(self, filename):
        """
        使用filename初始化一个workbook
        :param filename:filename需要带路径，后缀为.xlsx,例如：‘./demo.xlsx’
        """
        self.filename = filename
        self.workbook = xlsxwriter.Workbook(filename)

    def write_data(self, sheet_name, header, data):
        """
        向excel中写入数据
        :param sheet_name: 新建的sheet名称
        :param header: 每个sheet中的标题，格式为：['标题1','标题2','标题3']
        :param data: 数据，二维数组，每一行表示一个行，如[[1,2,3],[4,5,6],[7,8,9]]
        """
        worksheet = self.workbook.add_worksheet(sheet_name)
        worksheet.write_row("A1", header)
        for i in range(0, len(data)):
            worksheet.write_row(i + 1, 0, data[i])

    def close(self):
        """
        关闭workbook流
        :return:
        """
        self.workbook.close()

    @staticmethod
    def write_excel_by_row(out_file, headers, data):
        """
        写入到Excel的静态方法
        :param out_file: 输出地址，后缀为.xlsx
        :param headers: 输出到Excel的标题，格式为['标题1','标题2','标题3']
        :param data: 输出到Excel的数据，格式为[[1,2,3],[4,5,6]],按照行来组织
        :return: 无返回
        """
        excel_util = ExcelUtil(out_file)
        excel_util.write_data('sheet1', header=headers, data=data)
        excel_util.close()
